"""
非对称加密与RSA
"""

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64


message = 'hello world，你好，世界'     # todo 消息原文

# todo 1.初始化RSA对象
rsa = RSA.generate(1024, Random.new().read)
# todo 生成私钥
private_key = rsa.exportKey()
# todo 生成公钥
public_key = rsa.publickey().exportKey()
# todo 打印私钥和公钥
print(private_key.decode('utf-8'))
print(public_key.decode('utf-8'))

# 2. 将私钥和公钥存入对应名称的文件
with open('private.pem', 'wb') as fp:
    fp.write(private_key)

with open('public.pem', 'wb') as fp:
    fp.write(public_key)


# todo 3.用公钥加密消息原文
with open('public.pem') as fp:
    # todo 从文件中加载公钥
    pub = fp.read()
    publicKey = RSA.importKey(pub)
    # todo 用公钥加密消息原文
    cipher = PKCS1_v1_5.new(publicKey)
    c = base64.b64encode(cipher.encrypt(message.encode('utf-8'))).decode('utf-8')

# todo 4.用私钥解密消息密文
with open('private.pem') as fp:
    # todo 从文件中加载私钥
    pri = fp.read()
    privateKey = RSA.importKey(pri)
    # todo 用私钥解密消息密文
    cipher = PKCS1_v1_5.new(privateKey)
    m = cipher.decrypt(base64.b64decode(c), 'error').decode('utf-8')

print(f'消息原文：{message}')
print(f'消息密文：{c}')
print(f'解密结果：{m}')